//
//  AppDelegate.m
//  kabu
//
//  Created by XiangDongMBP on 2016/12/20.
//  Copyright © 2016年 East. All rights reserved.
//

#import "AppDelegate.h"
#import "KABLoginVC.h"
#import "KABRootTabVC.h"
#import "GlobalHeader.h"
#import "UIColor+XDHex.h"
#import "XDRsa.h"
#import "XDAFNetworking.h"
#import "ApiManager.h"
#import "KABModel.h"
#import <IQKeyboardManager.h>
#import <YYWebImage.h>
#import "WXApiManager.h"
#import "KABCosplayDetailVC.h"
#import "KABCosplayReplyVC.h"
#import <Bugly/Bugly.h>
// 引入JPush功能所需头文件
#import "JPUSHService.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
#import "ThemeManager.h"
#import <RongIMKit/RongIMKit.h>
#import "KABOperateVC.h"
#import "LauOpeManager.h"

@interface AppDelegate ()<JPUSHRegisterDelegate, RCIMUserInfoDataSource, RCIMReceiveMessageDelegate>//WXApiDelegate

@end

@implementation AppDelegate

#pragma mark - life cycle
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    // 初始化Bugly
    [Bugly startWithAppId:KABGlobalBuglyAppId];
    // 读取缓存
    if ([[KABModel sharedInstance] getFromDisk]) {
        NSLog(@"初始化缓存成功！");
    } else {
        NSLog(@"初始化缓存失败！");
    }
    // 配置全局的界面属性
    [self setGlobalAppearance];
    // 一些初始化信息、微信SDK、极光SDK、融云SDK
    [self starupInfoWithOptions:launchOptions];
    // 自动登录(由于用密码登录orToken登录，登录成功Token会更新，老的Token会失效。导致首页的请求一定会拿着老的失效的Token，所以就会每次都弹出登录界面。鉴于此，才取消了自动登录。)
    // [self autoLogin];
    // 但是对于需要更新Login用户信息的话，没有登录就不能更新用户信息。所以这里考虑加一个接口来获取用户信息。
    [self refreshLoginInfo];
    
    // 是否显示广告页面
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    UIImage *launchImg = [LauOpeManager sharedManager].launchOperateImg;
    if (launchImg) {
        KABOperateVC *vc = [[KABOperateVC alloc] init];
        vc.launchImg = launchImg;
        self.window.rootViewController = vc;
    } else {
        self.window.rootViewController = [[KABRootTabVC alloc] init];
    }
    [self.window makeKeyAndVisible];
    
    // 下载新的广告
    [[LauOpeManager sharedManager] downloadLaunchOperateImg];
    
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    // 保存数据到磁盘
    if ([[KABModel sharedInstance] saveToDisk]) {
        NSLog(@"保存数据到磁盘成功！");
    }else{
        NSLog(@"保存数据到磁盘失败！");
    }
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    
    // 显示状态栏
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
    // 显示状态栏
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
    
    /// 融云需要推送
    NSString *rcToken = [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<" withString:@""] stringByReplacingOccurrencesOfString:@">" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""];
    [[RCIMClient sharedRCIMClient] setDeviceToken:rcToken];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#pragma mark- JPUSHRegisterDelegate
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    NSLog(@"iOS10前台收到推送%@", userInfo);
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    NSLog(@"iOS10后台收到了推送%@", userInfo);     //!< iOS10本地推送也会走这个接口，那iOS8、iOS9呢？
    // 处理推送
    [self handlePushWithUserInfo:userInfo];
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // 处理推送
    [self handlePushWithUserInfo:userInfo];
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    NSLog(@"收到本地推送：%@", notification.userInfo);
    [self handlePushWithUserInfo:notification.userInfo];
}

#pragma mark - delegate
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
}
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
}
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
}

#pragma mark - 全局页面属性设置
//全局设置导航栏的颜色，TabBar的颜色
- (void)setGlobalAppearance {
    // 显示状态栏
    [[UIApplication sharedApplication] setStatusBarHidden:NO
                                            withAnimation:UIStatusBarAnimationFade];
    
//    //UINavigationBar
//    UINavigationBar *navBar = [UINavigationBar appearance];
//    
//    [navBar setBarTintColor:[UIColor blackColor]];
//    [navBar setTintColor:[UIColor whiteColor]];
//    NSDictionary *textAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor],
//                                     NSFontAttributeName: [UIFont systemFontOfSize:18]};
//    [navBar setTitleTextAttributes:textAttributes];
//    
////    navBar.backIndicatorImage = [UIImage imageNamed:@"global_nav_back"];
////    navBar.backIndicatorTransitionMaskImage = [UIImage imageNamed:@"global_nav_back"];
//    
//    // 返回的图片
//    UIImage *backImg = [UIImage imageNamed:@"global_nav_back"];
//    [[UIBarButtonItem appearance] setBackButtonBackgroundImage:backImg
//                                                      forState:UIControlStateNormal
//                                                    barMetrics:UIBarMetricsDefault];
//    
//    //UIBarButtonItem
//    NSDictionary * barItemAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor],
//                                         NSFontAttributeName: [UIFont systemFontOfSize:14]};
//    [[UIBarButtonItem appearance] setTitleTextAttributes:barItemAttributes forState:UIControlStateNormal];
//    
//    //TabBar
//    [[UITabBar appearance] setTintColor:[UIColor xd_colorWithHex:KABGlobalColorTabBarItemColor]];
//    NSDictionary * itemAttributes = @{NSFontAttributeName: [UIFont systemFontOfSize:9]};
//    [[UIBarItem appearance] setTitleTextAttributes:itemAttributes forState:UIControlStateNormal];
    
    [[ThemeManager sharedManager] setLaunchTheme];
}

- (void)starupInfoWithOptions:(NSDictionary *)launchOptions {
    // 键盘的全局隐藏
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    // 特定界面禁止
    [[IQKeyboardManager sharedManager].disabledDistanceHandlingClasses addObject:[KABCosplayDetailVC class]];
    [[IQKeyboardManager sharedManager].disabledDistanceHandlingClasses addObject:[KABCosplayReplyVC class]];
    [[IQKeyboardManager sharedManager].disabledDistanceHandlingClasses addObject:[RCConversationViewController class]];
    
    // 设置图片缓存时长
    YYImageCache *cache = [YYWebImageManager sharedManager].cache;
    cache.diskCache.ageLimit = 30 * 24 * 60 * 60;   // 30天
    
    // 向微信注册
    [WXApi registerApp:KABGlobalWeChatAppId];
    
    // 极光推送
    //Required
    //notice: 3.0.0及以后版本注册可以这样写，也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    // Required
    // init Push
    // notice: 2.1.5版本的SDK新增的注册方法，改成可上报IDFA，如果没有使用IDFA直接传nil
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    [JPUSHService setupWithOption:launchOptions appKey:KABGlobalJPushAppKey
                          channel:@"App Store"
                 apsForProduction:1
            advertisingIdentifier:nil];
    
    // 融云初始化
    [[RCIM sharedRCIM] initWithAppKey:KABGlobalRongCloudAppKey];
    // 融云用户信息的代理
    [RCIM sharedRCIM].userInfoDataSource = self;
    // 融云接收消息的代理
    [RCIM sharedRCIM].receiveMessageDelegate = self;
    // 融云IM上线
    [[KABModel sharedInstance] rongCloudOnLine];
    
    //清空icon图标的上的消息数量标识
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    // 清空通知栏的推送通知
    [JPUSHService removeNotification:nil];
}

#pragma mark - RCIMUserInfoDataSource
- (void)getUserInfoWithUserId:(NSString *)userId completion:(void (^)(RCUserInfo *))completion {
    RCUserInfo *defaultUser = [[RCUserInfo alloc] initWithUserId:userId name:@"" portrait:@""];
    if (!userId.length) {
        completion(defaultUser);
        return;
    }
    
    NSDictionary *pars = @{@"user_id" : userId};
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiMineUserSimpleInfo] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            NSLog(@"获取用户信息返回：%@", responseObject);
            KABMineIMUserInfo *userInfo = [KABMineIMUserInfo yy_modelWithDictionary:responseObject[KABGlobalJsonKeyResult]];
            RCUserInfo *user = [[RCUserInfo alloc] initWithUserId:userId name:userInfo.imName portrait:userInfo.user_headimg_url];
            [[RCIM sharedRCIM] refreshUserInfoCache:user withUserId:userId];
            completion(user);
        } else {
            completion(defaultUser);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        completion(defaultUser);
    }];
}

#pragma mark - RCIMReceiveMessageDelegate
- (void)onRCIMReceiveMessage:(RCMessage *)message left:(int)left {
    if (left <= 0) {
        if ([RCIMClient sharedRCIMClient].getTotalUnreadCount > 0) {
            // 提醒小红点(放到主线程去通知)
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiMsgRedDotShow object:nil userInfo:nil];
            });
        }
    }
}

#pragma mark - 推送处理
- (void)handlePushWithUserInfo:(NSDictionary *)userInfo {
    //清空icon图标的上的消息数量标识
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    // 清空通知栏的推送通知
    [JPUSHService removeNotification:nil];
    
    // 目前只处理kabu本身的消息推送
    if (userInfo[@"kabu"]) {
        self.pushDictionary = userInfo;
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiPushProcess object:nil userInfo:nil];
    }
}

#pragma mark - 自动登录
- (void)autoLogin {
    NSString * pwd = [[NSUserDefaults standardUserDefaults] objectForKey:KABGlobalUserDefaultsPwd];
    if (!pwd.length) {
        NSLog(@"未登录过，无法自动登录");
        [self wxAutoLogin];
        return;
    }
    NSString * account = [[NSUserDefaults standardUserDefaults] objectForKey:KABGlobalUserDefaultsAccount];
    if (!account.length) {
        NSLog(@"未登录过，无法自动登录");
        [self wxAutoLogin];
        return;
    }
    
    NSInteger timestramp = [[NSDate date] timeIntervalSince1970];
    NSDictionary *dic = @{@"password" : pwd,
                          @"timestamp": @(timestramp)};
    NSString *token = [XDRsa base64EncryptWithDictionary:dic];
    NSDictionary *pars = @{@"account"  : account,
                           @"token"    : token};
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiLogin] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"自动登录返回成功：%@", responseObject);
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [[KABModel sharedInstance] loginModelWithDictionary:responseObject];
            [[KABModel sharedInstance] saveUserInfoWithPwd:pwd];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"自动登录失败：%@", error);
    }];
}

- (void)wxAutoLogin {
    NSString * wxToken = [[NSUserDefaults standardUserDefaults] objectForKey:KABGlobalUserDefaultsWXAccessToken];
    if (!wxToken.length) {
        NSLog(@"微信未登录过，无法自动登录");
        return;
    }
    
    NSDictionary *pars = @{@"accesstoken"  : wxToken};
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiWXAccessTokenLogin] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"微信登录返回成功：%@", responseObject);
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [[KABModel sharedInstance] loginModelWithDictionary:responseObject];
            [[KABModel sharedInstance] saveWxAccessToken];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"微信登录失败：%@", error);
    }];
}

- (void)refreshLoginInfo {
    // 没有登录，就不需要刷新用户信息了
    if (![KABModel sharedInstance].isLogin) {
        return;
    }
    
    // 点赞请求
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token};

    [[XDAFNetworking sharedInstance] GET:[ApiManager apiRefreshUserInfo] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"刷新用户信息返回成功：%@", responseObject);
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [[KABModel sharedInstance] loginModelWithDictionary:responseObject];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"刷新用户失败：%@", error);
    }];
}

@end
